NOTES: Testing Observable JS

JavaScript
Author

Earl Potters

Published

May 3, 2025

Interactive Data Visualization with Observable JS

Observable JS is a powerful way to create interactive data visualizations within Quarto documents. Let’s explore a simple example that demonstrates reactive data binding and visualization.

data = [
  {category: "A", value: 28},
  {category: "B", value: 55},
  {category: "C", value: 43},
  {category: "D", value: 91},
  {category: "E", value: 81},
  {category: "F", value: 53},
  {category: "G", value: 19},
  {category: "H", value: 87}
]

// Create an input slider
viewof multiplier = Inputs.range(
  [0.1, 3], 
  {value: 1, step: 0.1, label: "Data multiplier:"}
)

// Apply the multiplier reactively
scaled_data = data.map(d => ({
  category: d.category,
  value: d.value * multiplier
}))

// Create a bar chart using Plot
Plot.plot({
  marginLeft: 60,
  y: {label: "Value"},
  marks: [
    Plot.barY(scaled_data, {x: "category", y: "value", fill: "steelblue", tip: true}),
    Plot.ruleY([0])
  ]
})

Adding Color Control

We can enhance our visualization by adding more interactive controls:

viewof color = Inputs.select(
  ["steelblue", "orange", "green", "purple", "red"],
  {value: "steelblue", label: "Bar color:"}
)

// Create a bar chart with user-selected color
Plot.plot({
  marginLeft: 60,
  y: {label: "Value"},
  marks: [
    Plot.barY(scaled_data, {x: "category", y: "value", fill: color, tip: true}),
    Plot.ruleY([0])
  ]
})

Data Table View

Observable JS also makes it easy to display your data in multiple formats:

// Display the data in a table
Inputs.table(scaled_data)

How Reactivity Works

The power of Observable JS lies in its reactive runtime. When you change the slider value, all calculations that depend on multiplier are automatically recomputed, and any visualizations that depend on those calculations are redrawn.

This reactivity makes it easy to create interactive dashboards without writing complex event handling code.

Next Steps

To create more complex visualizations with Observable JS, you can:

  1. Use data from external sources with FileAttachment() or fetch APIs
  2. Implement more complex interactions between multiple visualizations
  3. Incorporate advanced D3.js visualizations
  4. Use Observable’s built-in libraries for specialized visualizations

Check out the Observable documentation for more examples and tutorials.